//创建开发环境变量
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
//打包分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
    .BundleAnalyzerPlugin;
//Zopfli 压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const zopfli = require('@gfx/zopfli');
const BrotliPlugin = require('brotli-webpack-plugin');
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;


const path = require('path');
const resolve = dir => path.join(__dirname, dir);
const webpack = require('webpack');



module.exports = {
    publicPath: IS_PROD ? process.env.VUE_APP_PUBLIC_PATH : './', // 默认'/'，部署应用包时的基本 URL
    // outputDir: process.env.outputDir || 'dist', // 'dist', 生产环境构建文件的目录
    // assetsDir: "", // 相对于outputDir的静态资源(js、css、img、fonts)目录
    lintOnSave: false,
    runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
    productionSourceMap: !IS_PROD, // 生产环境的 source map
    parallel: require('os').cpus().length > 1,
    pwa: {},
    devServer: {
        overlay: { // 让浏览器 overlay 同时显示警告和错误
            warnings: true,
            errors: true
        },
        host: "localhost",
        port: "8888", // 代理断就
        https: false,
        hotOnly: false, // 热更新
        //解决跨域问题
        proxy: {
            '/api': {
                target:
                    'https://jsonplaceholder.typicode.com', // 目标代理接口地址
                secure: false,
                changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
                // ws: true, // 是否启用websockets
                pathRewrite: {
                    '^/api': ''
                }
            }
        },
    },
    configureWebpack: config => {
        //配置 externals 引入 cdn 资源
        config.externals = {
            vue: 'Vue',
            'vue-router': 'VueRouter',
            vuex: 'Vuex',
            axios: 'axios',
            'iView':'view-design'
        };
        //单独打包第三方模块
        if (IS_PROD) {
            config.optimization = {
                splitChunks: {
                    cacheGroups: {
                        libs: {
                            name: 'chunk-libs',
                            test: /[\\/]node_modules[\\/]/,
                            priority: 10,
                            chunks: 'initial'
                        },
                        elementUI: {
                            name: 'chunk-elementUI',
                            priority: 20,
                            test: /[\\/]node_modules[\\/]element-ui[\\/]/,
                            chunks: 'all'
                        }
                    }
                }
            }
        }
        //Zopfli 压缩
        const plugins = []
        if (IS_PROD) {
            plugins.push(
                new CompressionWebpackPlugin({
                    algorithm(input, compressionOptions, callback) {
                        return zopfli.gzip(input, compressionOptions, callback)
                    },
                    compressionOptions: {
                        numiterations: 15
                    },
                    minRatio: 0.99,
                    test: productionGzipExtensions
                })
            )
            plugins.push(
                new BrotliPlugin({
                    test: productionGzipExtensions,
                    minRatio: 0.99
                })
            )
        }
        config.plugins = [...config.plugins, ...plugins]
    },
    chainWebpack: config => {
        //单独打包第三方模块
        if (IS_PROD) {
            config.optimization.delete('splitChunks')
        }
        // 修复HMR   热加载失效
        config.resolve.symlinks(true);
        //添加别名
        config.resolve.alias
            .set('vue$', 'vue/dist/vue.esm.js')
            .set('@', resolve('src'))
            .set('@assets', resolve('src/assets'))
            .set('@scss', resolve('src/assets/scss'))
            .set('@components', resolve('src/components'))
            .set('@plugins', resolve('src/plugins'))
            .set('@views', resolve('src/views'))
            .set('@router', resolve('src/router'))
            .set('@store', resolve('src/store'))
            .set('@layouts', resolve('src/layouts'))
            .set('@static', resolve('src/static'))
        //压缩图片
        config.module
            .rule('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({
                mozjpeg: { progressive: true, quality: 65 },
                optipng: { enabled: false },
                pngquant: { quality: [0.65, 0.9], speed: 4 },
                gifsicle: { interlaced: false },
                webp: { quality: 75 }
            });
        // 打包分析
        if (process.env.IS_ANALY) {
            config.plugin('webpack-report').use(BundleAnalyzerPlugin, [
                {
                    analyzerMode: 'static'
                }
            ])
        }
        //引入cdn资源
        const cdn = {
            // 访问https://unpkg.com/view-design/dist/styles/iview.css获取最新版本
            css: ['https://unpkg.com/view-design/dist/styles/iview.css'],
            js: [
                // 访问https://unpkg.com/vue/dist/vue.min.js获取最新版本
                'https://unpkg.com/vue@2.6.10/dist/vue.min.js',
                'https://unpkg.com/vue-router@3.0.6/dist/vue-router.min.js',
                'https://unpkg.com/vuex@3.1.1/dist/vuex.min.js',
                'https://unpkg.com/axios@0.19.0/dist/axios.min.js',
                'https://unpkg.com/view-design/dist/iview.min.js'
            ]
        };
        // html中添加cdn
        config.plugin('html').tap(args => {
            args[0].cdn = cdn
            return args
        });
        //删除moment语言包
        config.plugin('ignore')
            .use(new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/))
        return config;
    }
}